package com.hckj.managersystemdemo.controller;

import com.hckj.managersystemdemo.entity.Users;
import com.hckj.managersystemdemo.repository.UsersRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class LoginController {
    //配置了WebMvcConfig之后，这里就不用写了
//    @RequestMapping("/")
//    public String test(){
//        return "login.html";
//    }
    @Autowired
    private UsersRepository usersRepository;
    @RequestMapping("/user/login")
    public String login(ModelMap map, Users users, HttpSession session){
        map.addAttribute("username",users.getUsername());
        //进行用户名密码的校验
        if(!StringUtils.isEmpty(users.getUsername())&&!StringUtils.isEmpty(users.getPassword())&&
                "root".equals(users.getUsername())&&"root".equals(users.getPassword())){
            //登录成功，把当前user对象注入到session中，进入拦截器里配置
            session.setAttribute("userInfo",users);
            //redirect 重定向
            return "redirect:/user/list";
        }else{
            //添加属性
            map.addAttribute("login_error","用户名密码错误");
            //去到登录页面
            return "login.html";
        }
    }
    @RequestMapping("/user/list")
    public String show(ModelMap map){
        List<Users> list = usersRepository.findAll();
        map.addAttribute("list",list);
        return "list.html";
    }
    @RequestMapping("/user/delete")
    public String delete(int id){
        usersRepository.deleteUserById(id);
        //不需要重定向，是因为前端做了删除操作
        return "list";
    }
    @RequestMapping("/add.do")
    public String add(Users user){
        usersRepository.addUser(user);
        //redirect 重定向
        return "redirect:/user/list";
    }
    @RequestMapping("update.do")
    public String update(Users user){
        usersRepository.deleteUserById(user.getId());
        usersRepository.addUser(user);
        //redirect 重定向
        return "redirect:/user/list";
    }
}
